#!/usr/bin/python
# -*- coding : UTF-8 -*-
# ========================
# @Time  : 2020/5/7 14:04
# @Author: Mecell
# @File  : config_packaging.py
# ========================
import os
from configparser import ConfigParser

from common.path_constants import BASIC_INFO_CONF, CONFIG_DIR,USER_ACCOUNT_CONF,RE_CONF



class ConfigHandle(ConfigParser):
    """
    定义处理配置文件的类
    """
    def __init__(self, filename=None):
        super().__init__()
        self.filename = filename
        self.read(self.filename, encoding="utf-8")

    def __call__(self, section="DEFAULT", option=None, eval_flag=None, bool_flag=None):
        if option is None:
            return dict(self[section])
        value = self[section][option]

        if isinstance(bool_flag, bool):
            if bool_flag:
                return self.getboolean(section, option)

        if isinstance(eval_flag, bool):
            if eval_flag:
                return eval(value)

        if value.isdigit():
            return int(value)
        try:
            return float(value)
        except ValueError:
            pass

        return value

    @classmethod
    def write_config(cls, data, filename):
        config_obj = cls(filename=filename)
        for key in data:
            config_obj[key] = data[key]
        filename = os.path.join(CONFIG_DIR, filename)
        with open(filename, 'w', encoding='utf-8') as conf_file:
            config_obj.write(conf_file)


config_obj = ConfigHandle(BASIC_INFO_CONF)

if __name__ == '__main__':
    # print(config_obj())
    # print(config_obj("mysql"))
    # print(config_obj("mysql", "host"))
    # print(config_obj("log info", "log_bkCount"), type(config_obj("log info", "log_bkCount")))
    # print(config_obj(option="b"), type(config_obj(option="b")))
    # print(config_obj(option="a", eval_flag=True), type(config_obj(option="a", eval_flag=True)))
    # print(config_obj(option="c", bool_flag=True), type(config_obj(option="c", bool_flag=True)))
    config = ConfigHandle(USER_ACCOUNT_CONF)
    print(type(config("emp user")),config("emp user"))

    print(config("admin user")['username'])



